from  .Base import Base
from ..util.Wechat import Wechat

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from time import sleep

class Book(Base):
    wechat = Wechat()
    bookId = ''
    categoryId = ''

    product = False

    def __init__(self, url, categoryId):
        Base.__init__(self, url)
        self.categoryId = categoryId

    def isElementExist(self,selector):
        try:
            ele = self.driver.find_element_by_css_selector(selector)
            return True
        except:
            return False
        
       
    def start(self):
        self.getBook(self.categoryId)
        aList = self.driver.find_elements_by_css_selector('.sons a')
        list = []
        for a in aList:
            list.append(a.get_attribute('href'))
        
        return
        

        
        for index,item in enumerate(list):
            self.driver.get(item)
           
            try:
                self.getChater(index)
            except:
                pass
            
        
           

    def getBook(self, categoryId):
        name = self.driver.find_element_by_css_selector('.cont b').text
        desc = self.driver.find_elements_by_css_selector('.cont p')[1].text
      
        if self.product:

            self.bookId = self.wechat.addBook(name=name, categoryId=categoryId, author='', desc=desc, order=1)
        else:
            print(categoryId)
            print(name, desc)

    def getChater(self, order):    
        # 名称
        name = self.driver.find_element_by_css_selector('.sons b').text
        
       
        # 原文
        yuanWen = self.driver.find_element_by_css_selector('.contson ').get_attribute('innerHTML')
        yuanWen = self.clearStr(yuanWen)
       
        # 译文
        if (self.isElementExist("div[id^='fanyi'] a:last-child")):
            aEl = self.driver.find_element_by_css_selector("div[id^='fanyi'] a:last-child")
            aEl.click()
            el = WebDriverWait(self.driver, 30, 0.2).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div[id^='fanyiquan'] .contyishang")))
            
        else:
            el = self.driver.find_elements_by_css_selector(".contyishang")[0]
          
        yiWen = el.get_attribute('outerHTML')
        yiWen = self.clearStr(yiWen)

       

       
        if self.product:
            chapterName = name
            self.wechat.addChapter(bookId=self.bookId, name=chapterName, original=yuanWen,translation=yiWen,order=order)
        else:
            print(self.bookId)
            print(yuanWen)
            print(yiWen)

    def clearStr(self, str):
        str = str.replace('\r', '')
        str = str.replace('\n', '')
        # str = str.replace('"', '“')
        # str = str.replace("'", "‘")
        return str
           
        